package site.param.config;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import site.param.util.PropertiesUtils;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by Administrator on 2017/1/3.
 */
@MapperScan("site.dao.**.mapper")
@Configuration    //该注解类似于spring配置文件
public class MyBatisConfig {

    public MyBatisConfig(){
        System.out.println("sql init  ...");
    }
    /**
     * 创建数据源
     */
    @Bean
    public DataSource dataSource1() throws Exception{
        Properties props = new Properties();
        props.put("driverClassName", PropertiesUtils.findPorpertyByKey("spring.datasource.driver-class-name","mysql_db1.properties"));
        props.put("url", PropertiesUtils.findPorpertyByKey("spring.datasource.url","mysql_db1.properties"));
        props.put("username", PropertiesUtils.findPorpertyByKey("spring.datasource.username","mysql_db1.properties"));
        props.put("password", ConfigTools.decrypt(PropertiesUtils.findPorpertyByKey("password.publicKey","mysql_db1.properties"),PropertiesUtils.findPorpertyByKey("spring.datasource.password","mysql_db1.properties")));

        return DruidDataSourceFactory.createDataSource(props);
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(dataSource1());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        fb.setMapperLocations(resolver.getResources(PropertiesUtils.findPorpertyByKey("mybatis.mapperLocations","mysql_db1.properties")));
        fb.setTypeAliasesPackage(PropertiesUtils.findPorpertyByKey("mybatis.typeAliasesPackage","mysql_db1.properties"));//指定基包
        return fb.getObject();
    }




    @Bean
    public PlatformTransactionManager transactionManager() {
        try{
            return new DataSourceTransactionManager(dataSource1());

        }catch (Exception e){
            e.printStackTrace();
        }
        return  null;
    }

}